package com.zbkj.service.service.project.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.zbkj.common.constants.RedisKeyConstants;
import com.zbkj.common.enums.ProjectStatusEnum;
import com.zbkj.common.enums.ReportApplyStatusEnum;
import com.zbkj.common.exception.CommonException;
import com.zbkj.common.model.project.ProjectInfo;
import com.zbkj.common.page.CommonPage;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.common.vo.project.ProjectModifyConditionVo;
import com.zbkj.common.vo.project.ProjectQueryVo;
import com.zbkj.service.dao.project.ProjectInfoMapper;
import com.zbkj.service.service.project.ProjectInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 项目信息表 服务实现类
 * </p>
 *
 * @author 
 * @since 2024-07-06
 */
@Service
public class ProjectInfoServiceImpl extends ServiceImpl<ProjectInfoMapper, ProjectInfo> implements ProjectInfoService {

    @Resource
    private ProjectInfoMapper projectInfoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public PageInfo<ProjectInfo> projectList(ProjectQueryVo queryVo, int page, int limit) {
        LambdaQueryWrapper<ProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectInfo::getDeleteFlag, 0);
        if(CollectionUtils.isNotEmpty(queryVo.getStatusList())) {
            queryWrapper.in(ProjectInfo::getStatus, queryVo.getStatusList());
        }
        if(Objects.nonNull(queryVo.getUserId())) {
            queryWrapper.eq(ProjectInfo::getUserId,queryVo.getUserId());
        }
        if(StringUtils.isNotBlank(queryVo.getProjectName())) {
            queryWrapper.like(ProjectInfo::getProjectName, queryVo.getProjectName());
        }
        if(Objects.nonNull(queryVo.getSourceType())) {
            queryWrapper.like(ProjectInfo::getSourceType, queryVo.getSourceType());
        }
        if(StringUtils.isNotBlank(queryVo.getBeginDate())) {
            queryWrapper.ge(ProjectInfo::getCreateTime, queryVo.getBeginDate());
        }
        if(StringUtils.isNotBlank(queryVo.getEndDate())) {
            queryWrapper.le(ProjectInfo::getCreateTime, queryVo.getEndDate());
        }
        /*if(Objects.nonNull(queryVo.getRemindFlag())) {
            queryWrapper.eq(ProjectInfo::getRemindFlag, queryVo.getRemindFlag());
        }*/
        if(StringUtils.isNotBlank(queryVo.getKeyword())) {
            queryWrapper.and(wrapper->wrapper.like(ProjectInfo::getProjectName,queryVo.getKeyword())
                    .or().like(ProjectInfo::getCompanyName,queryVo.getKeyword()));
        }
        if(Objects.nonNull(queryVo.getProjectType())) {
            queryWrapper.eq(ProjectInfo::getProjectType,queryVo.getProjectType());
        }
        //设置排序规则
        this.projectQueryListSort(queryWrapper, queryVo.getStatusSort(), queryVo.getSource());
        Page<ProjectInfo> pageObj = PageHelper.startPage(page, limit);
        List<ProjectInfo> list = this.list(queryWrapper);
        return CommonPage.copyPageInfo(pageObj, list);
    }

    @Override
    public Integer projectNameRepeatCheck(Long userId, String projectName, Long id) {
        return projectInfoMapper.projectNameRepeatCheck(userId, projectName, id);
    }

    @Override
    public boolean updateProject(ProjectInfo projectInfo, ProjectModifyConditionVo conditionVo) {
        if(Objects.isNull(projectInfo) || Objects.isNull(projectInfo.getId())) {
            return false;
        }
        LambdaUpdateWrapper<ProjectInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProjectInfo::getDeleteFlag, 0)
                .eq(ProjectInfo::getId, projectInfo.getId());
        if(Objects.nonNull(conditionVo)) {
            if(CollectionUtils.isNotEmpty(conditionVo.getStatusList())) {
                updateWrapper.in(ProjectInfo::getStatus, conditionVo.getStatusList());
            }
            if(CollectionUtils.isNotEmpty(conditionVo.getNeStatusList())) {
                updateWrapper.notIn(ProjectInfo::getStatus, conditionVo.getNeStatusList());
            }
            if(Objects.nonNull(conditionVo.getVersionNum())) {
                //版本号幂等处理
                updateWrapper.setSql("version_num = version_num +1 ");
                updateWrapper.eq(ProjectInfo::getVersionNum, conditionVo.getVersionNum());
            }
            if(CollectionUtils.isNotEmpty(conditionVo.getReportApplyStatusList())) {
                //报告申请|审批更新时 报告申请状态条件
                updateWrapper.in(ProjectInfo::getReportApplyStatus, conditionVo.getReportApplyStatusList());
            }
            if(StringUtils.isNotBlank(conditionVo.getAireqNo())) {
                //检查ai请求流水号
                updateWrapper.eq(ProjectInfo::getAireqNo,conditionVo.getAireqNo());
            }
        }
        return this.update(projectInfo, updateWrapper);
    }

    @Override
    public Integer getProjectStatusCount(List<Integer> statusList, Integer remindFlag, Long userId) {
        LambdaQueryWrapper<ProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectInfo::getDeleteFlag,0);
        queryWrapper.in(ProjectInfo::getStatus, statusList);
        /*if(Objects.nonNull(remindFlag)) {
            queryWrapper.eq(ProjectInfo::getRemindFlag,remindFlag);
        }*/
        if(Objects.nonNull(userId)) {
            queryWrapper.eq(ProjectInfo::getUserId,userId);
        }
        return this.count(queryWrapper);
    }

    @Override
    public boolean projectLockUpdate(Long projectId, int lockState) {
        if(Objects.isNull(projectId) || projectId.longValue() <0) {
            return false;
        }
        /*LambdaUpdateWrapper<ProjectInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ProjectInfo::getLockState, lockState)
                .eq(ProjectInfo::getDeleteFlag,0)
                .eq(ProjectInfo::getId, projectId);
        boolean flag = this.update(updateWrapper);
        if(flag && lockState == 1) {
            //锁定后-删除密码错误计数缓存
            String pwdErrorkey = String.format(RedisKeyConstants.PROJECT_PWDERROR_KEY,projectId);
            redisUtil.delete(pwdErrorkey);
        }
        return flag;*/
        return true;
    }

    @Override
    public void withdrawnAttrInit(ProjectInfo projectInfo) {
        projectInfo.setStatus(ProjectStatusEnum.WITHDRAWN.getStatus());
        //projectInfo.setRemindFlag(0);
        //projectInfo.setEstimateSource(0);
        projectInfo.setEstimateFlag(0);
        projectInfo.setReportApplyStatus(ReportApplyStatusEnum.UN_APPLY.getStatus());
        projectInfo.setReportFlag(0);
    }

    @Override
    public void projectRestInit(ProjectInfo projectInfo) {
        projectInfo.setEstimateFlag(0);
        projectInfo.setAiNotfiyFlag(0);
        projectInfo.setReportApplyStatus(ReportApplyStatusEnum.UN_APPLY.getStatus());
        projectInfo.setReportFlag(0);
        if(Objects.isNull(projectInfo.getBudgetAmount())) {
            projectInfo.setBudgetAmount(BigDecimal.ZERO);
        }
        projectInfo.setSoftwarePoints(BigDecimal.ZERO);
        projectInfo.setSoftwareFun(BigDecimal.ZERO);
        projectInfo.setSoftwareFee(BigDecimal.ZERO);
        projectInfo.setAisoftwarePoints(BigDecimal.ZERO);
        projectInfo.setAisoftwareFun(BigDecimal.ZERO);
        projectInfo.setAisoftwareFee(BigDecimal.ZERO);
    }


    @Override
    public Integer getProjectUserCount(Long userId) {
        LambdaQueryWrapper<ProjectInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectInfo::getDeleteFlag,0);
        queryWrapper.eq(ProjectInfo::getUserId,userId);
        return this.count(queryWrapper);
    }

    @Override
    public List<Long> getHandleDemoPrjectIds(List<String> fileNameList, Date delayDate) {
        if(CollectionUtils.isEmpty(fileNameList)) {
            return Lists.newArrayList();
        }
        return projectInfoMapper.getHandleDemoPrjectIds(fileNameList,delayDate);
    }

    @Override
    public void reportApplyStatusUpdate(Long projectId, Integer applyStatus) {
        if(Objects.isNull(projectId)) {
            throw new CommonException("项目更新申请状态确认少项目ID参数");
        }
        ProjectInfo updateProject = new ProjectInfo();
        updateProject.setId(projectId);
        updateProject.setReportApplyStatus(applyStatus);
        ProjectModifyConditionVo conditionVo = new ProjectModifyConditionVo();
        //设置更新检查条件
        conditionVo.setStatusList(Lists.newArrayList(ProjectStatusEnum.COMPLET_ESTIMATE.getStatus()));
        if(ReportApplyStatusEnum.isUnStatus(applyStatus)) { //订单手工|自动取消更新为待申请
            //报告申请状态检查条件
            conditionVo.setReportApplyStatusList(Lists.newArrayList(ReportApplyStatusEnum.IN_APPLY.getStatus()));
        } else if(ReportApplyStatusEnum.isInStatus(applyStatus)) { //更新为申请中
            //报告申请状态检查条件
            conditionVo.setReportApplyStatusList(ReportApplyStatusEnum.applyCheckStatusList());
        } else if(ReportApplyStatusEnum.isRejectStatus(applyStatus)) { //拒绝申请
            //报告申请状态检查条件
            conditionVo.setReportApplyStatusList(Lists.newArrayList(ReportApplyStatusEnum.IN_APPLY.getStatus()));
        } else if(ReportApplyStatusEnum.isPassStatus(applyStatus)) { //申请通过
            updateProject.setReportApplyStatus(ReportApplyStatusEnum.PASS_APPLY.getStatus());
            updateProject.setReportStartTime(new Date());
            updateProject.setStatus(ProjectStatusEnum.IN_REPORT.getStatus());
        } else {
            throw new CommonException("报告申请状态参数错误");
        }
        boolean updateFlag = this.updateProject(updateProject, conditionVo);
        if(!updateFlag) {
            throw new CommonException("项目信息已变更，请稍后再试");
        }
    }

    /**
     * 项目列表查询排序规则：设置排序规则
     * @param queryWrapper
     * @param statusSort
     * @param source
     */
    private void projectQueryListSort(LambdaQueryWrapper<ProjectInfo> queryWrapper, Integer statusSort, int source) {
        if(Objects.isNull(statusSort)) {
            queryWrapper.orderByDesc(ProjectInfo::getCreateTime);
            return;
        }
        if(source == 0) { //服务端端排序
            if(ProjectStatusEnum.isToEstimate(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getCreateTime);
            } else if(ProjectStatusEnum.isInEstimate(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getEstimateBeginTime);
            } else if(ProjectStatusEnum.isCompletEstimate(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getEstimateEndTime);
            } else if(ProjectStatusEnum.isInReport(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getReportStartTime);
            } else if(ProjectStatusEnum.isFinish(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getCompleteTime);
            }
        } else { //客户端排序
            if(ProjectStatusEnum.isToEstimate(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getCreateTime);
            } else if(ProjectStatusEnum.isInEstimate(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getEstimateBeginTime);
            } else if(ProjectStatusEnum.isCompletEstimate(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getEstimateConfirmTime);
            } else if(ProjectStatusEnum.isInReport(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getReportStartTime);
            } else if(ProjectStatusEnum.isFinish(statusSort)) {
                queryWrapper.orderByDesc(ProjectInfo::getCompleteTime);
            }
        }
    }
}
